"""
try:
    可能发生异常的代码
except:
    处理异常的代码
else:
    没有发生异常，except不满足执行else
finally:
    不管有没有异常，最终都要执行
====================================
try:
    执行更新数据库(增删改)的sql语句
except:
   有异常，回滚事务
else:
    没有异常，提交事务
finally:
    关闭游标和连接对象
"""

import pymysql

connect = pymysql.connect(host='211.103.136.244', port=7061, user='student', password='iHRM_student_2021',
                          database='test_db', charset='utf8')

cursor = connect.cursor()

sql = "INSERT INTO t_book(title,pub_date,`read`,`comment`,is_delete) VALUES('龙卷风','1999-01-01',100,200,0)"

try:
    # 执行语句
    num = cursor.execute(sql)
    print(num)
except Exception as e:
    # 回滚事务
    print('执行错误：',e)
    connect.rollback()
else:
    # 提交事务
    connect.commit()
finally:
    # 关闭
    cursor.close()
    connect.close()
